#include <iostream>
#include <json/json.h>
#include <json/reader.h>
#include <json/value.h>
#include <json/writer.h>
#include <memory>
#include <sstream>
#include <string>

bool Serialize(const Json::Value& obj, std::string& dst)
{
    // 使用 Json::StreamWriter 序列化前需要先使用 工厂类 Json::StreamWriterBuilder 进行实例化
    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());

    std::stringstream ss;
    int ret = sw->write(obj, &ss);
    if(ret) {
        std::cerr << "json序列化失败\n";
        return false;
    }
    dst = ss.str();
    return true;
}

bool DeSerialize(const std::string& src, Json::Value& obj)
{
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

    std::string error_msg; 
    if(false == cr->parse(src.data(), src.data() + src.size(), &obj, &error_msg)) {
        std::cerr << "json反序列化失败\n";
        return false;
    }
    return true;
}

int main()
{
    char name[] = "小美";
    int age = 18;
    double score[3] = {66, 77.5, 88.2};

    Json::Value stu;
    stu["姓名"] = name;
    stu["年龄"] = age;
    stu["成绩"].append(score[0]);
    stu["成绩"].append(score[1]);
    stu["成绩"].append(score[2]);

    std::string stu_str;
    bool ret = Serialize(stu, stu_str);
    if(!ret) return 1;
    std::cout << stu_str << '\n';

    Json::Value src;
    ret = DeSerialize(stu_str, src);
    if(!ret) return 1;
    std::cout << src["姓名"].asString() << '\n';
    std::cout << src["年龄"].asString() << '\n';
    int n = src["成绩"].size();
    for(int i = 0; i < n; ++i) {
        std::cout << src["成绩"][i].asDouble() << '\n';
    }
    return 0;
}